package main

import (
	"fmt"
	"sort"
)

func main() {
	arr := []int{10, 30, 40, 20}
	res := arrayRankTransform(arr)
	fmt.Println(res)
}

type SortItem struct {
	val   int
	index int
}

func arrayRankTransform(arr []int) []int {
	if len(arr) == 0 {
		return arr
	}
	sortArr := make([]SortItem, 0)
	for i, val := range arr {
		sortArr = append(sortArr, SortItem{val, i})
	}
	sort.Slice(sortArr, func(i, j int) bool {
		return sortArr[i].val < sortArr[j].val
	})
	revRank := 1
	arr[sortArr[0].index] = 1
	for i := 1; i < len(sortArr); i++ {
		if sortArr[i].val > sortArr[i-1].val {
			revRank++
		}
		arr[sortArr[i].index] = revRank
	}
	return arr
}
